/*
 *    Copyright 2008-2009 The Digester Tools Team
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.digestertools.annotations.utils;

import java.lang.annotation.Annotation;

import org.apache.commons.beanutils.MethodUtils;

/**
 * 
 * @author Simone Tripodi
 * @version $Id: AnnotationUtils.java 357 2009-12-16 20:00:36Z simone.tripodi $
 */
public class AnnotationUtils {

    private static final String VALUE = "value";

    private static final String PATTERN = "pattern";

    private AnnotationUtils() {
        // this class can' be instantiated
    }

    public static Object getAnnotationValue(Annotation annotation) {
        return invokeAnnotationMethod(annotation, VALUE);
    }

    public static String getAnnotationPattern(Annotation annotation) {
        Object ret = invokeAnnotationMethod(annotation, PATTERN);
        if (ret != null) {
            return (String) ret;
        }
        return null;
    }

    public static Annotation[] getAnnotationsArrayValue(Annotation annotation) {
        Object value = getAnnotationValue(annotation);
        if (value != null
                && value.getClass().isArray()
                && Annotation.class.isAssignableFrom(value.getClass().getComponentType())) {
            return (Annotation[]) value;
        }
        return null;
    }

    private static Object invokeAnnotationMethod(Annotation annotation, String method) {
        try {
            return MethodUtils.invokeExactMethod(annotation, method, null);
        } catch (Exception e) {
            return null;
        }
    }

}
